package com.hanbang.chu_xing_gao_zhao.activity.camera;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.hanbang.chu_xing_gao_zhao.application.MyApplication;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.cxgz_2.R;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

/**
 * Created by Administrator on 2016/2/25.
<<<<<<< HEAD
 *
 *
=======
 *22222
>>>>>>> b59a9d3935c48dfc1ddd2717b231eb6ba5587469
 * 1:CameraVideo.startActivity(MeActivity.this);
 * 2:if (requestCode == CameraVideo.FINSH_INTENT_FLAG && resultCode == CameraVideo.FINSH_INTENT_FLAG) {
 *        String filePath = data.getStringExtra("filePath");
 *     }
 */
public class CameraVideo extends Activity implements SurfaceHolder.Callback {
    private MediaRecorder mediarecorder;// 录制视频的类
    private SurfaceView surfaceview;// 显示视频的控件
    // 用来显示视频的一个接口，我靠不用还不行，也就是说用mediarecorder录制视频还得给个界面看
    // 想偷偷录视频的同学可以考虑别的办法。。嗯需要实现这个接口的Callback接口
    private SurfaceHolder surfaceHolder;
    private TextView startTv, stopTv, timeTv;
    private String fileName = null;
    public static int FINSH_INTENT_FLAG = 1024;

    /**
     * 0：停止
     * 1:正在录制
     */
    private int status = 0;
    private int time = 0;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        // 设置横屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        // 选择支持半透明模式,在有surfaceview的activity中使用。
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.camear_video);
        initView();
    }

    public static void startActivity(Activity activity) {
        Intent intent = new Intent(activity, CameraVideo.class);
        activity.startActivityForResult(intent, FINSH_INTENT_FLAG);
    }

    private void initView() {
        startTv = (TextView) findViewById(R.id.start);
        stopTv = (TextView) findViewById(R.id.stop);
        timeTv = (TextView) findViewById(R.id.time);
        stopTv.setEnabled(false);
        startTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTv.setEnabled(false);
                startTv.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startTv.setEnabled(true);
                    }
                }, 2000);

                if (start()) {
                    startTv.setText("重录");
                    stopTv.setEnabled(true);
                } else {
                    startTv.setText("开始");
                    mediarecorder.release();
                    stopTv.setEnabled(false);
                }

            }
        });
        stopTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(fileName)) {
                    stop();
                    String path = MyApplication.cameraPath + "/" + fileName;
                    File f = new File(path);
                    if (f.exists()) {
                        setResult(FINSH_INTENT_FLAG, new Intent().putExtra("filePath", path));
                    }
                    finish();
                }
            }
        });

        surfaceview = (SurfaceView) this.findViewById(R.id.surfaceview);
        SurfaceHolder holder = surfaceview.getHolder();// 取得holder
        holder.addCallback(this); // holder加入回调接口
    }

    private void initMediaRecorder() {
        mediarecorder = new MediaRecorder();// 创建mediarecorder对象
        // 设置录制视频源为Camera(相机)
        mediarecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
        mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
        mediarecorder
                .setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        // 设置录制的视频编码h263 h264
        mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        // 设置视频录制的分辨率。必须放在设置编码和格式的后面，否则报错
        mediarecorder.setVideoSize(1920, 1080);
        // 设置录制的视频帧率。必须放在设置编码和格式的后面，否则报错
        // mediarecorder.setVideoFrameRate(30);
        mediarecorder.setVideoEncodingBitRate((int) Math.round(1.5 * 1024 * 512));// 设置帧频率，然后就清晰了
        mediarecorder.setPreviewDisplay(surfaceHolder.getSurface());
        // 设置视频文件输出的路径
        fileName = getDate() + ".mp4";

        mediarecorder.setOutputFile(MyApplication.cameraPath + "/" + fileName);

        mediarecorder.setOnInfoListener(onInfoListener);
    }

    private boolean start() {
        stop();
        initMediaRecorder();
        try {
            // 准备录制
            mediarecorder.prepare();
            // 开始录制
            mediarecorder.start();
            time = 0;
            status = 1;
            if (adSwitchTask == null) {
                timeTv.post(adSwitchTask = new AdSwitchTask(this));
            }

        } catch (IOException e) {
            e.printStackTrace();
            fileName = null;
            return false;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            fileName = null;
            return false;
        }
        return true;
    }

    private void stop() {
        try {
            if (mediarecorder != null) {
                // 停止录制
                mediarecorder.stop();
                // 释放资源
                mediarecorder.release();
                mediarecorder = null;
                status = 0;
            }
        } catch (Exception e) {
        }

    }


    MediaRecorder.OnInfoListener onInfoListener = new MediaRecorder.OnInfoListener() {
        @Override
        public void onInfo(MediaRecorder mr, int what, int extra) {
            MyLog.e("onInfoListener", what + "   " + extra);
        }
    };


    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        // 将holder，这个holder为开始在oncreat里面取得的holder，将它赋给surfaceHolder
        surfaceHolder = holder;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // 将holder，这个holder为开始在oncreat里面取得的holder，将它赋给surfaceHolder
        surfaceHolder = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // surfaceDestroyed的时候同时对象设置为null
        surfaceview = null;
        surfaceHolder = null;
        mediarecorder = null;
    }

    /**
     * 获取系统时间
     */
    private String getDate() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }

    private AdSwitchTask adSwitchTask;

    static class AdSwitchTask implements Runnable {

        private final WeakReference<CameraVideo> reference;

        AdSwitchTask(CameraVideo cameraVideo) {
            this.reference = new WeakReference<CameraVideo>(cameraVideo);
        }

        @Override
        public void run() {
            CameraVideo cameraVideo = reference.get();
            if (cameraVideo != null && cameraVideo.status == 1) {
                cameraVideo.timeTv.setText(cameraVideo.getTimeToString(cameraVideo.time));
                cameraVideo.time++;
                cameraVideo.timeTv.postDelayed(cameraVideo.adSwitchTask, 1000);
            }
        }
    }

    private String getTimeToString(int time) {
        StringBuilder stringBuilder = new StringBuilder();
        if (time >= 0) {
            int hours = (time % (24 * 60 * 60)) / (60 * 60);
            int minutes = ((time % (24 * 60 * 60)) % (60 * 60)) / 60;
            int second = ((time % (24 * 60 * 60)) % (60 * 60)) % 60;
            stringBuilder.append(String.format("%02d", hours));
            stringBuilder.append(":");
            stringBuilder.append(String.format("%02d", minutes));
            stringBuilder.append(":");
            stringBuilder.append(String.format("%02d", second));
        } else {
            stringBuilder.append("00:00:00");
        }
        return stringBuilder.toString();

    }
}
